#include "scene_game.h"
#pragma execution_character_set("utf-8")
#include "scene_welcome.h"
#include "fstream"

using namespace cocos2d;

CCScene* scene_game::scene()
{
	CCScene * scene = NULL;
	scene = CCScene::create();
	scene_game *layer = scene_game::create();
	scene->addChild(layer);
	return scene;
}


bool scene_game::init()
{
	bool bRet = false;
	do
	{

		CC_BREAK_IF(!CCLayer::init());
		this->setTouchEnabled(true);
		CCSize size = CCDirector::sharedDirector()->getWinSize();
		CCSprite* pSprite = CCSprite::create("data\\bg_1.jpg");
		pSprite->setPosition(ccp(size.width / 2, size.height / 2 ));
		this->addChild(pSprite, 0);

		Audio::bg_play();
		CCLOG("scene_game   load sucessed");
	
		star = new Star(this);
		label = new Label(this);
		Audio::play_go();

		switch (rand() % 3)
		{
		case 0:CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("data\\gamebg1.mp3", true); break;
		case 1:CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("data\\gamebg0.mp3", true); break;
		case  2:CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("data\\boss1.mp3", true); break;
		default:
			break;
		}
		bRet = true;
	} while (0);

	return bRet;
}


void scene_game::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{

	CCSetIterator it = pTouches->begin();
	CCTouch* touch = (CCTouch*)(*it);
	CCPoint location = touch->getLocation();
	search_xy xy;
	xy.x = location.x / 48;
	xy.y = location.y / 48;
	if ((xy.x  >= 0 && xy.x < 10) && (xy.y < 10 && xy.y >= 0))
	if (star->Star_exit[xy.x][xy.y]!=100)
	{
		this->setTouchEnabled(false);
		star->will_search.push(xy);
		star->will_delete.push(xy);
		star->Search();
		int a = star->Delete();
		if (a!=0)
		label->Bonus(a);
		zz += a;
		label->setScore(zz);
		star->move_down();
		star->move_left();
		star->move_down();
		star->move_left();
		Audio::play_bonus(a);
		if (star->is_over() == true)
		{
			ofstream onfile("score.txt", ios::out);
			onfile << zz;
			onfile.close();
			this->removeAllChildren();
			
			star = new Star(this);
			label = new Label(this);
		}
		this->setTouchEnabled(true);
	}
	
}
